package com.yudaob2b.elong.task;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yudaob2b.business.entity.po.ElongHotelRatePO;
import com.yudaob2b.business.service.ElongHotelRateService;
import com.yudaob2b.elong.constant.RedisConstant;
import com.yudaob2b.elong.entity.dto.ELaElongHotelRateDTO;
import com.yudaob2b.elong.entity.vo.Rate;
import com.yudaob2b.elong.enums.ela.EnumElasticElongIndexName;
import com.yudaob2b.elong.service.HotelRateService;
import org.apache.commons.lang.StringUtils;
import org.frameworkset.elasticsearch.client.ClientInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 价格入库线程
 *
 * @author Kidd.Tan
 * @email 298023780@qq.com
 * @date 7/20/18 8:42 PM
 */
public class DataRateLocalDbTask implements Runnable, Serializable {
    private static Logger dataRateLocalDbTaskLogger = LoggerFactory.getLogger("dataRateLocalDbTaskLogger");

    private List<Rate> rateList;
    private ElongHotelRateService elongHotelRateService;
    private RedisTemplate redisTemplate;
    private HotelRateService hotelRateService;
    private ClientInterface clientUtil;

    public DataRateLocalDbTask(List<Rate> rateList, ElongHotelRateService elongHotelRateService
            , RedisTemplate redisTemplate, HotelRateService hotelRateService, ClientInterface clientUtil) {
        this.rateList = rateList;
        this.elongHotelRateService = elongHotelRateService;
        this.redisTemplate = redisTemplate;
        this.hotelRateService = hotelRateService;
        this.clientUtil = clientUtil;
    }

    @Override
    public void run() {
        // 保存搜索引擎
        saveEla();
        // 数据库持久化
        //saveDb()
    }

    /**
     * 保存搜索引擎
     */
    private void saveEla() {
        // 待插入列表
        List<ELaElongHotelRateDTO> newList = new ArrayList();
        for (Rate rate : rateList) {
            if (rate.getMember().compareTo(BigDecimal.valueOf(-1)) > 0 && rate.getWeekend().compareTo(BigDecimal.valueOf(-1)) > 0) {
                ELaElongHotelRateDTO dto = hotelRateService.getElaDtoByRate(rate);
                newList.add(dto);
            }
        }
        if (newList.size() > 0) {
            clientUtil.addDocuments(EnumElasticElongIndexName.RATE.getIndexName(),//索引表
                    EnumElasticElongIndexName.RATE.getType(),//索引类型
                    newList);
        }
        //dataRateLocalDbTaskLogger.info("---价格入库线程总耗时：-insert:{},--{}", newList.size(),  System.currentTimeMillis() - start);
    }

    /**
     * 数据库持久化
     */
    private void saveDb() {
        // 待插入列表
        List<ElongHotelRatePO> newList = new ArrayList();
        // 待更新列表
        List<ElongHotelRatePO> updateList = new ArrayList();
        // 缓存就酒店价格列表
        List<ElongHotelRatePO> oldElongHotelRateList = null;
        String hotelIdTemp = "";
        for (Rate rate : rateList) {
            if (rate.getMember().compareTo(BigDecimal.valueOf(-1)) > 0 && rate.getWeekend().compareTo(BigDecimal.valueOf(-1)) > 0) {
                ElongHotelRatePO elongHotelRatePO = hotelRateService.getPoByRate(rate);
                newList.add(elongHotelRatePO);
                /*if (StringUtils.isEmpty(hotelIdTemp) || !hotelIdTemp.equals(elongHotelRatePO.getHotelId())) {
                    hotelIdTemp = elongHotelRatePO.getHotelId();
                    String key = RedisConstant.REDIS_CACHE_RATE_KEY.replace("{hotelId}", elongHotelRatePO.getHotelId());
                    if (!redisTemplate.hasKey(key)) {
                        EntityWrapper<ElongHotelRatePO> ew = new EntityWrapper<>();
                        ew.where("hotel_id={0}", elongHotelRatePO.getHotelId());
                        oldElongHotelRateList = elongHotelRateService.selectList(ew);
                    } else {
                        oldElongHotelRateList = (List<ElongHotelRatePO>) redisTemplate.opsForValue().get(key);
                    }
                }

                // 检查当前elongHotelRatePO是否已经存在
                if (oldElongHotelRateList != null && oldElongHotelRateList.size() > 0) {
                    int flag = 0;
                    for (ElongHotelRatePO cacheRate : oldElongHotelRateList) {
                        if (cacheRate.getHotelId().equals(elongHotelRatePO.getHotelId())
                                && cacheRate.getRoomTypeId().equals(elongHotelRatePO.getRoomTypeId())
                                && cacheRate.getRatePlanId().equals(elongHotelRatePO.getRatePlanId())
                                && cacheRate.getStartDate().compareTo(elongHotelRatePO.getStartDate()) == 0
                                && cacheRate.getEndDate().compareTo(elongHotelRatePO.getEndDate()) == 0) {
                            updateList.add(elongHotelRatePO);
                            flag = 1;
                            break;
                        }
                    }
                    if (flag == 0) {
                        newList.add(elongHotelRatePO);
                    }
                } else {
                    newList.add(elongHotelRatePO);
                }*/
            }
        }

        elongHotelRateService.replaceInto(newList);
        /*if (newList.size() > 0) {
            elongHotelRateService.insertBatch(newList);
        }
        if (updateList.size() > 0) {
            elongHotelRateService.updateBatch(updateList);
        }*/
        //dataRateLocalDbTaskLogger.info("---价格入库线程总耗时：-insert:{}, update:{}--{}", newList.size(), updateList.size(), System.currentTimeMillis() - start3);
    }
}
